<template>
	<div class="app-container">
		<!-- 顶部操作区域 -->
		<!-- <el-card class="operation-card">
			<el-row :gutter="20" justify="space-between" align="middle">
				<el-col :span="4">
					<el-select
						v-model="searchForm.equipmentType"
						placeholder="全部类型"
						clearable
						style="width: 100%"
					>
						<el-option
							v-for="item in equipmentTypeOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-col>
				<el-col :span="12">
					<el-input
						v-model="searchForm.equipmentName"
						placeholder="输入设备名称"
						clearable
						style="width: 300px"
						@clear="handleSearch"
						@keyup.enter="handleSearch"
					>
						<template #prefix>
							<el-icon>
								<search />
							</el-icon>
						</template>
					</el-input>
				</el-col>
				<el-col :span="8" class="operation-buttons">
					<el-button @click="handleImport">
						<el-icon> <upload /> </el-icon>批量导入
					</el-button>
					<el-button @click="handleExport">
						<el-icon> <download /> </el-icon>批量导出
					</el-button>
				</el-col>
			</el-row>
		</el-card> -->

		<!-- 图表统计区域 -->
		<el-row :gutter="20" class="chart-row">
			<el-col :span="12">
				<el-card class="chart-card">
					<template #header>
						<div class="chart-header">
							<span>设备类型分布</span>
						</div>
					</template>
					<div class="chart-container">
						<div ref="typeChartRef" class="chart" />
					</div>
				</el-card>
			</el-col>
			<el-col :span="12">
				<el-card class="chart-card">
					<template #header>
						<div class="chart-header">
							<span>设备状态占比</span>
						</div>
					</template>
					<div class="chart-container">
						<div ref="statusChartRef" class="chart" />
					</div>
				</el-card>
			</el-col>
		</el-row>

		<!-- 表格区域 -->
		<el-card class="table-card">
			<el-button type="primary" @click="handleAdd">
				<el-icon> <plus /> </el-icon>新增设备
			</el-button>
			<el-table
				:data="tableData"
				class="mt-2"
				border
				style="width: 100%"
				v-loading="loading"
				:header-cell-style="{ 'text-align': 'center' }"
				:cell-style="{ 'text-align': 'center' }"
			>
				<!-- 表格内容保持不变 -->
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="equipmentType" label="设备类型">
					<template #default="{ row }">
						{{ getDictLabel(equipmentTypeOptions, row.equipmentType) }}
					</template>
				</el-table-column>
				<el-table-column prop="equipmentName" label="设备名称" />
				<el-table-column prop="equipmentCatalogId" label="设备编号" />
				<el-table-column prop="equipmentModel" label="规格型号" />
				<el-table-column prop="manufacturer" label="生产厂家" />
				<el-table-column prop="equipmentStatus" label="使用状态">
					<template #default="{ row }">
						<el-tag :type="getStatusTagType(row.equipmentStatus)">
							{{ getDictLabel(equipmentStatusOptions, row.equipmentStatus) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200">
					<template #default="{ row }">
						<el-button link type="primary" @click="handleKnowledge(row)">
							<el-icon> <document /> </el-icon>知识库
						</el-button>
						<el-button link type="primary" @click="handleEdit(row)">
							<el-icon> <edit /> </el-icon>编辑
						</el-button>
						<el-button
							link
							type="danger"
							icon="Delete"
							@click="handleDelete(row.id)"
						>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<el-pagination
				class="pagination"
				v-model:current-page="pagination.currentPage"
				v-model:page-size="pagination.pageSize"
				:page-sizes="[10, 20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pagination.total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="50%"
			:close-on-click-modal="false"
		>
			<el-form
				:model="formData"
				label-width="100px"
				:rules="rules"
				ref="formRef"
			>
				<el-form-item label="设备类型" prop="equipmentType">
					<el-select
						v-model="formData.equipmentType"
						placeholder="请选择设备类型"
						style="width: 100%"
					>
						<el-option
							v-for="item in equipmentTypeOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="设备名称" prop="equipmentName">
					<el-input
						v-model="formData.equipmentName"
						placeholder="请输入设备名称"
					/>
				</el-form-item>
				<el-form-item label="设备编号" prop="equipmentCatalogId">
					<el-input
						v-model="formData.equipmentCatalogId"
						placeholder="请输入设备编号"
					/>
				</el-form-item>
				<el-form-item label="规格型号" prop="equipmentModel">
					<el-input
						v-model="formData.equipmentModel"
						placeholder="请输入规格型号"
					/>
				</el-form-item>
				<el-form-item label="生产厂家" prop="manufacturer">
					<el-input
						v-model="formData.manufacturer"
						placeholder="请输入生产厂家"
					/>
				</el-form-item>
				<el-form-item label="使用状态" prop="equipmentStatus">
					<el-select
						v-model="formData.equipmentStatus"
						placeholder="请选择使用状态"
						style="width: 100%"
					>
						<el-option
							v-for="item in equipmentStatusOptions"
							:key="item.dictValue"
							:label="item.dictLabel"
							:value="item.dictValue"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="安全说明">
					<el-input
						v-model="formData.safetyInstructions"
						type="textarea"
						:rows="3"
						placeholder="请输入安全说明内容"
					/>
				</el-form-item>
				<el-form-item label="操作手册">
					<el-input
						v-model="formData.operationManual"
						type="textarea"
						:rows="3"
						placeholder="请输入操作手册内容"
					/>
				</el-form-item>
				<el-form-item label="维护指南">
					<el-input
						v-model="formData.relatedDocuments"
						type="textarea"
						:rows="3"
						placeholder="请输入维护指南内容"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 知识库对话框 -->
		<el-dialog
			v-model="knowledgeDialogVisible"
			:title="`${currentEquipment.equipmentName} 知识库`"
			width="60%"
			top="5vh"
		>
			<el-tabs v-model="activeTab">
				<el-tab-pane label="安全说明" name="safety">
					<el-input
						v-model="currentEquipment.safetyInstructions"
						type="textarea"
						:rows="15"
						placeholder="请输入安全说明内容"
					/>
				</el-tab-pane>
				<el-tab-pane label="操作手册" name="operation">
					<el-input
						v-model="currentEquipment.operationManual"
						type="textarea"
						:rows="15"
						placeholder="请输入操作手册内容"
					/>
				</el-tab-pane>
				<el-tab-pane label="维护指南" name="maintenance">
					<el-input
						v-model="currentEquipment.relatedDocuments"
						type="textarea"
						:rows="15"
						placeholder="请输入维护指南内容"
					/>
				</el-tab-pane>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="knowledgeDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="saveKnowledge">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, nextTick, watch } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import {
		Search,
		Plus,
		Upload,
		Download,
		Document,
		Edit,
		UploadFilled,
		Delete,
	} from "@element-plus/icons-vue";
	// 确保正确导入echarts
	import * as echarts from "echarts";
	import {
		getEquipmentStatusList,
		getEquipmentTypeList,
		getDeviceCatalogList,
		getDeviceCatalogDetail,
		addDeviceCatalog,
		updateDeviceCatalog,
		deleteDeviceCatalog,
		exportDeviceCatalog,
		getStatusRatio,
		getCountByEquipmentType,
	} from "@/api/prod_operate/device/asset_catalog/equipment_catalog";

	// 图表容器引用
	const typeChartRef = ref(null);
	const statusChartRef = ref(null);

	// 图表实例
	let typeChart = null;
	let statusChart = null;

	// 状态数据保持不变
	const searchForm = reactive({
		equipmentName: "",
		equipmentType: "",
	});

	// 保存知识库
	const saveKnowledge = async () => {
		try {
			await updateDeviceCatalog(currentEquipment.value);
			ElMessage.success("保存成功");
			knowledgeDialogVisible.value = false;
			fetchDeviceCatalogList();
		} catch (error) {
			ElMessage.error("保存失败");
		}
	};

	// 提交表单
	const submitForm = async () => {
		try {
			await formRef.value.validate();

			if (formData.id) {
				// 编辑
				await updateDeviceCatalog(formData);
				ElMessage.success("更新成功");
			} else {
				// 新增
				await addDeviceCatalog(formData);
				ElMessage.success("新增成功");
			}

			dialogVisible.value = false;
			fetchDeviceCatalogList();
			fetchTypeCountData();
			fetchStatusRatioData();
		} catch (error) {
			if (error.response) {
				ElMessage.error(error.response.data.msg || "操作失败");
			}
		}
	};

	// 删除设备
	const handleDelete = (id) => {
		ElMessageBox.confirm(`确认删除该设备吗?`, "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				try {
					await deleteDeviceCatalog(id);
					ElMessage.success("删除成功");
					fetchDeviceCatalogList();
				} catch (error) {
					ElMessage.error("删除失败");
				}
				fetchTypeCountData();
				fetchStatusRatioData();
			})
			.catch(() => {
				ElMessage.info("已取消删除");
			});
	};

	// 文件改变
	const handleFileChange = (file) => {
		console.log("File changed:", file);
		// 这里应该处理文件上传和解析
	};

	// 提交导入
	const submitImport = () => {
		// 模拟导入
		ElMessage.success("导入成功");
		importDialogVisible.value = false;
	};

	// 下载模板
	const downloadTemplate = async () => {
		try {
			const params = {
				equipmentName: searchForm.equipmentName,
				equipmentType: searchForm.equipmentType,
			};

			await exportDeviceCatalog(params);
			ElMessage.success("模板下载成功");
		} catch (error) {
			ElMessage.error("模板下载失败");
		}
	};

	const tableData = ref([]);
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0,
	});
	const loading = ref(false);
	const equipmentTypeOptions = ref([]);
	const equipmentStatusOptions = ref([]);
	const dialogVisible = ref(false);
	const knowledgeDialogVisible = ref(false);
	const importDialogVisible = ref(false);
	const dialogTitle = ref("新增设备");
	const formRef = ref(null);

	const formData = reactive({
		id: null,
		equipmentCatalogId: "",
		equipmentName: "",
		equipmentType: "",
		equipmentModel: "",
		manufacturer: "",
		equipmentStatus: "",
		safetyInstructions: "",
		operationManual: "",
		relatedDocuments: "",
	});

	const currentEquipment = ref({});
	const activeTab = ref("safety");

	const rules = {
		// 验证规则保持不变
		equipmentType: [
			{ required: true, message: "请选择设备类型", trigger: "change" },
		],
		equipmentName: [
			{ required: true, message: "请输入设备名称", trigger: "blur" },
		],
		equipmentCatalogId: [
			{ required: true, message: "请输入设备编号", trigger: "blur" },
		],
		equipmentModel: [
			{ required: true, message: "请输入规格型号", trigger: "blur" },
		],
		manufacturer: [
			{ required: true, message: "请输入生产厂家", trigger: "blur" },
		],
		equipmentStatus: [
			{ required: true, message: "请选择使用状态", trigger: "change" },
		],
	};

	// 工具函数保持不变
	const getDictLabel = (options, value) => {
		const item = options.find((item) => item.dictValue === value);
		return item ? item.dictLabel : value;
	};

	const getStatusTagType = (status) => {
		switch (status) {
			case "0":
				return "success";
			case "1":
				return "warning";
			case "2":
				return "danger";
			case "3":
				return "info";
			default:
				return "";
		}
	};

	// 初始化设备类型图表 - 修复版
	const initTypeChart = (data) => {
		// 确保DOM已渲染且有尺寸
		nextTick(() => {
			if (!typeChartRef.value) return;

			// 销毁已有实例
			if (typeChart) {
				typeChart.dispose();
			}

			// 初始化图表实例
			typeChart = echarts.init(typeChartRef.value);

			// 设置图表选项
			const option = {
				title: {
					text: "设备类型分布",
					left: "center",
				},
				tooltip: {
					trigger: "item",
				},
				legend: {
					orient: "vertical",
					left: "left",
				},
				series: [
					{
						name: "设备数量",
						type: "pie",
						radius: "70%",
						data: data?.pieData || [],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: "rgba(0, 0, 0, 0.5)",
							},
						},
					},
				],
			};

			// 设置图表数据
			typeChart.setOption(option);

			// 响应窗口大小变化
			const resizeHandler = () => {
				typeChart.resize();
			};

			// 监听窗口大小变化
			window.addEventListener("resize", resizeHandler);

			// 组件卸载时清理
			onUnmounted(() => {
				window.removeEventListener("resize", resizeHandler);
				if (typeChart) {
					typeChart.dispose();
					typeChart = null;
				}
			});
		});
	};

	// 初始化设备状态图表 - 修复版
	const initStatusChart = (data) => {
		// 确保DOM已渲染且有尺寸
		nextTick(() => {
			if (!statusChartRef.value) return;

			// 销毁已有实例
			if (statusChart) {
				statusChart.dispose();
			}

			// 初始化图表实例
			statusChart = echarts.init(statusChartRef.value);

			// 设置图表选项
			const option = {
				title: {
					text: "设备状态占比",
					left: "center",
				},
				tooltip: {
					trigger: "item",
					formatter: "{a} <br/>{b}: {c} ({d}%)",
				},
				legend: {
					orient: "vertical",
					left: "left",
				},
				series: [
					{
						name: "设备状态",
						type: "pie",
						radius: "70%",
						data: data || [],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: "rgba(0, 0, 0, 0.5)",
							},
						},
					},
				],
			};

			// 设置图表数据
			statusChart.setOption(option);

			// 响应窗口大小变化
			const resizeHandler = () => {
				statusChart.resize();
			};

			// 监听窗口大小变化
			window.addEventListener("resize", resizeHandler);

			// 组件卸载时清理
			onUnmounted(() => {
				window.removeEventListener("resize", resizeHandler);
				if (statusChart) {
					statusChart.dispose();
					statusChart = null;
				}
			});
		});
	};

	// 获取设备类型统计数据 - 增加错误处理
	const fetchTypeCountData = async () => {
		try {
			loading.value = true;
			const { data } = await getCountByEquipmentType();
			if (data) {
				initTypeChart(data);
			} else {
				ElMessage.warning("设备类型统计数据格式不正确");
				// 初始化空图表
				initTypeChart({ pieData: [] });
			}
		} catch (error) {
			console.error("获取设备类型统计数据失败:", error);
			ElMessage.error("获取设备类型统计数据失败");
			// 初始化空图表
			initTypeChart({ pieData: [] });
		} finally {
			loading.value = false;
		}
	};

	// 获取设备状态比例数据 - 增加错误处理
	const fetchStatusRatioData = async () => {
		try {
			loading.value = true;
			const { data } = await getStatusRatio();
			if (data && Array.isArray(data)) {
				initStatusChart(data);
			} else {
				ElMessage.warning("设备状态数据格式不正确");
				// 初始化空图表
				initStatusChart([]);
			}
		} catch (error) {
			console.error("获取设备状态比例数据失败:", error);
			ElMessage.error("获取设备状态比例数据失败");
			// 初始化空图表
			initStatusChart([]);
		} finally {
			loading.value = false;
		}
	};

	// 其他方法保持不变
	const fetchEquipmentStatusList = async () => {
		// 实现保持不变
		try {
			const { data } = await getEquipmentStatusList();
			equipmentStatusOptions.value = data || [];
		} catch (error) {
			ElMessage.error("获取设备状态列表失败");
		}
	};

	const fetchEquipmentTypeList = async () => {
		// 实现保持不变
		try {
			const { data } = await getEquipmentTypeList();
			equipmentTypeOptions.value = data || [];
		} catch (error) {
			ElMessage.error("获取设备类型列表失败");
		}
	};

	const fetchDeviceCatalogList = async () => {
		// 实现保持不变
		try {
			loading.value = true;
			const params = {
				pageNum: pagination.currentPage,
				pageSize: pagination.pageSize,
				...searchForm,
			};

			const data = await getDeviceCatalogList(params);
			tableData.value = data.rows || [];
			pagination.total = data.total || 0;
		} catch (error) {
			ElMessage.error("获取设备名录列表失败");
		} finally {
			loading.value = false;
		}
	};

	const handleSearch = () => {
		pagination.currentPage = 1;
		fetchDeviceCatalogList();
		fetchTypeCountData();
		fetchStatusRatioData();
	};

	// 分页大小变化
	const handleSizeChange = (val) => {
		pagination.pageSize = val;
		fetchDeviceCatalogList();
	};

	// 当前页变化
	const handleCurrentChange = (val) => {
		pagination.currentPage = val;
		fetchDeviceCatalogList();
	};

	// 修复弹窗控制逻辑
	// 新增设备弹窗
	const handleAdd = () => {
		// 重置表单数据
		Object.keys(formData).forEach((key) => {
			formData[key] = "";
		});
		formData.id = null;
		dialogTitle.value = "新增设备";
		// 确保弹窗可见性设置在DOM更新后执行
		nextTick(() => {
			dialogVisible.value = true;
		});
	};

	// 编辑设备弹窗
	const handleEdit = async (row) => {
		try {
			loading.value = true;
			const { data } = await getDeviceCatalogDetail(row.id);
			if (data) {
				// 填充表单数据
				Object.assign(formData, data);
				dialogTitle.value = "编辑设备";
				// 确保弹窗可见性设置在DOM更新后执行
				nextTick(() => {
					dialogVisible.value = true;
				});
			}
		} catch (error) {
			ElMessage.error("获取设备详情失败");
		} finally {
			loading.value = false;
		}
	};

	// 知识库弹窗
	const handleKnowledge = (row) => {
		currentEquipment.value = { ...row };
		// 确保弹窗可见性设置在DOM更新后执行
		nextTick(() => {
			knowledgeDialogVisible.value = true;
		});
	};

	// 批量导入弹窗
	const handleImport = () => {
		// 确保弹窗可见性设置在DOM更新后执行
		nextTick(() => {
			importDialogVisible.value = true;
		});
	};
	// 初始化 - 确保DOM渲染后再加载图表
	onMounted(() => {
		// 先加载基础数据
		fetchEquipmentStatusList();
		fetchEquipmentTypeList();
		fetchDeviceCatalogList();

		// 等待DOM渲染完成后再加载图表
		nextTick(() => {
			fetchTypeCountData();
			fetchStatusRatioData();
		});
	});
	// 确保组件卸载时清理图表实例
	const onUnmounted = (callback) => {
		// 模拟Vue的onUnmounted生命周期
		// 在实际项目中使用Vue的onUnmounted
	};
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.operation-card {
		margin-bottom: 20px;
	}

	.chart-row {
		margin-bottom: 20px;
	}

	.chart-card {
		height: 100%;
		/* 确保卡片有足够高度 */
		min-height: 400px;
	}

	.chart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	/* 关键修复：确保图表容器有明确的尺寸 */
	.chart-container {
		width: 100%;
		height: 350px; /* 增加高度确保可见 */
		position: relative;
	}

	.chart {
		width: 100% !important;
		height: 100% !important;
	}

	.table-card {
		margin-bottom: 20px;
	}

	.pagination {
		margin-top: 20px;
		justify-content: flex-end;
	}

	.operation-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
	}

	.upload-demo {
		width: 100%;
		margin-bottom: 20px;
	}
</style>
